package me.zxk.smartagriculture.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zxk.smartagriculture.dto.note.NoteRequest;
import me.zxk.smartagriculture.dto.note.NoteResponse;
import me.zxk.smartagriculture.entity.Note;
import me.zxk.smartagriculture.repository.NoteRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 便签服务
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class NoteService {

    private final NoteRepository noteRepository;

    /**
     * 获取用户便签列表
     */
    public Page<NoteResponse> getUserNotes(Long userId, String keyword, Pageable pageable) {
        Page<Note> notePage;
        
        if (StringUtils.hasText(keyword)) {
            notePage = noteRepository.findByUserIdAndKeyword(userId, keyword, pageable);
        } else {
            notePage = noteRepository.findByUserId(userId, pageable);
        }
        
        return notePage.map(NoteResponse::fromEntity);
    }

    /**
     * 获取便签详情
     */
    public NoteResponse getNoteDetail(Long noteId, Long userId) {
        Note note = noteRepository.findByIdAndUserId(noteId, userId)
                .orElseThrow(() -> new RuntimeException("便签不存在或无权访问"));
        
        return NoteResponse.fromEntity(note);
    }

    /**
     * 创建便签
     */
    @Transactional
    public NoteResponse createNote(Long userId, NoteRequest request) {
        // 验证请求参数
        validateNoteRequest(request);
        
        Note note = new Note();
        note.setUserId(userId);
        note.setTitle(request.getTitle());
        note.setContent(request.getContent());
        
        Note savedNote = noteRepository.save(note);
        log.info("用户 {} 创建便签成功: {}", userId, savedNote.getId());
        
        return NoteResponse.fromEntity(savedNote);
    }

    /**
     * 更新便签
     */
    @Transactional
    public NoteResponse updateNote(Long noteId, Long userId, NoteRequest request) {
        // 验证请求参数
        validateNoteRequest(request);
        
        Note note = noteRepository.findByIdAndUserId(noteId, userId)
                .orElseThrow(() -> new RuntimeException("便签不存在或无权访问"));
        
        note.setTitle(request.getTitle());
        note.setContent(request.getContent());
        
        Note savedNote = noteRepository.save(note);
        log.info("用户 {} 更新便签成功: {}", userId, noteId);
        
        return NoteResponse.fromEntity(savedNote);
    }

    /**
     * 删除便签
     */
    @Transactional
    public void deleteNote(Long noteId, Long userId) {
        Note note = noteRepository.findByIdAndUserId(noteId, userId)
                .orElseThrow(() -> new RuntimeException("便签不存在或无权访问"));
        
        noteRepository.delete(note);
        log.info("用户 {} 删除便签成功: {}", userId, noteId);
    }

    /**
     * 批量删除便签
     */
    @Transactional
    public void batchDeleteNotes(Long userId, List<Long> noteIds) {
        if (noteIds == null || noteIds.isEmpty()) {
            throw new RuntimeException("便签ID列表不能为空");
        }
        
        noteRepository.deleteByUserIdAndIdIn(userId, noteIds);
        log.info("用户 {} 批量删除便签成功: {}", userId, noteIds);
    }

    /**
     * 获取用户便签数量
     */
    public long getUserNoteCount(Long userId) {
        return noteRepository.countByUserId(userId);
    }

    /**
     * 验证便签请求参数
     */
    private void validateNoteRequest(NoteRequest request) {
        if (!StringUtils.hasText(request.getTitle()) && !StringUtils.hasText(request.getContent())) {
            throw new RuntimeException("便签标题和内容不能同时为空");
        }
    }
}
